package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@Controller
public class CheckCodeController {
    @ResponseBody
    @RequestMapping("/changeImg")
    public void getImage(HttpServletResponse response, HttpServletRequest request) throws IOException {
        int width = 50;
        int height = 20;
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(new Color(255,255,255));
        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 19));
        graphics.fillRect(0,0,width,height);

        StringBuilder value = new StringBuilder();
        Random random = new Random();
        for (int i=0;i<2;i++){
            int number = random.nextInt(10);
            value.append(number);
            char ch = (char) (random.nextInt(25)+'a');
            value.append(ch);
        }
        graphics.setColor(new Color(230,23,34));
        String vercode = value.toString();
        request.getSession().setAttribute("vercode",vercode );
        graphics.drawString(vercode,5,height);
//        System.out.println(value.toString());
//        for (int i = 0; i <55 ; i++) {
//            int x = random.nextInt(width-12);
//            int y = random.nextInt(width-12);
//            int x1 = random.nextInt(12);
//            int y1 = random.nextInt(12);
//            graphics.setColor(new Color(x1,x+x1,y1+y1));
//            graphics.drawLine(x,y,x+x1,y+y1);
//        }
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        graphics.dispose();
        ImageIO.write(image,"JPEG",response.getOutputStream());
        return;
    }
}
